﻿using TrueSync;
using UnityEngine;

namespace HEFramework
{
    public static class ATKEffectViewSystem
    {
        [EntitySystem]
        public class ATKEffectViewAwakeSystem : AwakeSystem<ATKEffectView, int, TSVector>
        {
            protected override void Awake(ATKEffectView _self, int _a, TSVector _b)
            {
                var pc = _self.GetSceneChild<PrefabComponent>();
                var dc = _self.GetSceneChild<DataTableComponent>();
                if (pc == null || dc == null)
                {
                    return;
                }

                _self.ID = _a;
                var data = dc.LoadDataTable<DRATKEffect>().GetData(_self.ID);
                _self.Behaviour = pc.GetPrefabSyn(data.ABPath, data.ABName).GetComponent<TransformBehaviour>();
                _self.Behaviour.gameObject.transform.position = _b.ToVector();
            }
        }


        [EntitySystem]
        public class ATKEffectViewUpdateSystem : UpdateSystem<ATKEffectView>
        {
            protected override void Update(ATKEffectView _self)
            {
                _self.UpdatePos();
                _self.LookAtCamera();
            }
        }


        [EntitySystem]
        public class ATKEffectViewDestroySystem : DestroySystem<ATKEffectView>
        {
            protected override void Destroy(ATKEffectView _self)
            {
                if (_self.Behaviour == null)
                {
                    return;
                }

                var dc = _self.GetSceneChild<DataTableComponent>();
                var pc = _self.GetSceneChild<PrefabComponent>();
                if (dc == null || pc == null)
                {
                    GameObject.Destroy(_self.Behaviour.gameObject);
                    _self.Behaviour = null;
                    return;
                }

                var data = dc.LoadDataTable<DRATKEffect>().GetData(_self.ID);
                pc.Recycle(data.ABPath, data.ABName, _self.Behaviour.gameObject);
                _self.Behaviour = null;
            }
        }


        public static void UpdatePos(this ATKEffectView _self)
        {
            if (_self.Behaviour == null)
            {
                return;
            }

            var p = _self.GetParentChild<TransformComponent>().P;
            _self.Behaviour.gameObject.transform.position = p.ToVector();
            if (!_self.Behaviour.gameObject.activeSelf)
            {
                _self.Behaviour.gameObject.SetActive(true);
            }
        }


        public static void LookAtCamera(this ATKEffectView _self)
        {
            if (_self.Behaviour == null)
            {
                return;
            }

            var gc = _self.GetSceneChild<GameCamera>();
            if (gc == null)
            {
                return;
            }

            gc.SetGameObjectRotateToCamera(_self.Behaviour.GetTransform("Transform_Body"));
        }
    }
}